package com.sllp.C71S3TsllpShop.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.sllp.C71S3TsllpShop.bean.Address;
import com.sllp.C71S3TsllpShop.bean.Result;
import com.sllp.C71S3TsllpShop.bean.User;
import com.sllp.C71S3TsllpShop.biz.impl.AddressBizImpl;
import com.sllp.C71S3TsllpShop.biz.impl.UserBizImpl;
import com.sllp.C71S3TsllpShop.dao.AddressMapper;

@Controller
public class RegisterAction {

	@Resource
	private UserBizImpl ub;
	@Resource
	private AddressMapper am;
	
	@GetMapping("toRegist.do")
	public String toRegister(Model m) {
		m.addAttribute("result", new Result(1));
		return "Regist";
	}
	
	
	@PostMapping("registNow.do")
	public String toRegistNow(User user,String loginVerifyCode,Model m,@SessionAttribute("VerifyCode") String code) {
		//TODO 此验证码可改成邮箱验证码
		if(!loginVerifyCode.equals(code)) {
			m.addAttribute("result", new Result(0, "验证码错误"));
			return "Regist";
		}
		// 登录用户名默认为手机号/  邮箱？   考虑设置为邮箱，如果注册了则发送邮件确认...
		Address address = new Address();
		address.setName("默认地址请修改");
		address.setPostal("1111111");
		address.setState(2);
		address.setTel("12345678901");
		am.insertSelective(address);
		
		user.setLoginName(user.getTel());
		//TODO 这个字段考虑删除
		user.setLoginState(2);
		user.setState(3);
		user.setImage(1);
		user.setAddr(address.getId());
		
		// MD5加密
		String md5Password = DigestUtils.md5DigestAsHex(user.getPwd().getBytes());
		user.setPwd(md5Password);
		
		address.setUser(user.getId());
		am.updateByPrimaryKeySelective(address);
		
		Result result = ub.userRegist(user);
		if(result.getSucess()==0) {
			m.addAttribute("result", result);
			return "Regist";
		}
		m.addAttribute("result", result);
		return "redirect:toLogin.do";
	}
	
	
}
